#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/errno.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
typedef struct temp
{
    char ch[32];
    int true;
}temp,*ftemp;


int main(int argc,const char*  argv[]){

    key_t key = ftok("./app",'a');
    if(key < 0){
        perror("ftok err");
        return -1;
    }
    printf("%#x\n",key);

    int shmid = shmget(key,sizeof(temp),IPC_CREAT | IPC_EXCL | 0666);
    if(shmid <= 0){
        if(errno == EEXIST){
            shmid = shmget(key,sizeof(temp),0666);
        }else{
            perror("shmget err");
            return -1;
        }
    }

    printf("shmid:%d\n",shmid);

    ftemp fone=(void*)shmat(shmid,NULL,0);
    if(fone == (ftemp)-1){
        perror("shmat err");
        shmctl(shmid,IPC_RMID,NULL);//删除共享内存
        return -1;
    }
    memset(fone,0,sizeof(temp));

    while(1){
        
        scanf("%s",fone->ch);
        fone->true =1;//输入后便发送信号

        if(strcmp(fone->ch,"quit") == 0){
            break;
        }
        
        while(fone->true == 1)//等待true的值改变(等待进程发送信号)
        {
            sleep(1);
        }
    
    }
    if(shmdt(fone) == -1){//取消映射
        printf("shmdt err\n");
    }
   

    if(shmctl(shmid,IPC_RMID,NULL) == -1){//删除共享内存
        printf("shmctl err\n");
    }
    
    return 0;
}